<?php
namespace app\company\controller;

use think\Exception;
use think\Request;
use think\Db;
use app\company\logic\Export;
/**
 * 奖票管理
 */
class Ticket extends Base
{
    public function _initialize(){
        parent::_initialize();
    }

    //奖票事件
    public function index(Request $request){
        $prize_buckle_time = input('prize_buckle_time')??date('Y-m-01').' - '.date('Y-m-d');
        $prize_buckle_time_arr = explode(' - ', $prize_buckle_time);
        if(count($prize_buckle_time_arr) != 2){
            $prize_buckle_time_arr[] = date('Y-m-1');
            $prize_buckle_time_arr[] = date('Y-m-d');
        }
        $where = [
            'ipb.prize_buckle_time'=>[ ['>=', strtotime($prize_buckle_time_arr[0])], ['<=', strtotime($prize_buckle_time_arr[1])+86400-1], 'and' ],
            'ipb.status'=>2,
            'ieru.com_id'=>$this->com_id,
            'ieru.is_lottery_ticket'=>1
        ];

        $params = [
            'department_id'=>input('department_id', 0, 'intval'),
            'user_id'=>input('user_id', 0, 'intval'),
            'event_name'=>trim(input('event_name', '', 'addslashes')),
            'integral_b1'=>input('integral_b1', 0, 'intval'),
            'integral_b2'=>input('integral_b2', 0, 'intval'),
            'record_user_id'=>input('record_user_id', 0, 'intval'),
            'first_check_user_id'=>input('first_check_user_id', 0, 'intval'),
            'last_check_user_id'=>input('last_check_user_id', 0, 'intval'),
            'is_print'=>input('is_print', -1, 'intval'),
        ];

        if($params['department_id']){
            //查询下级分类
            $ids_a = department_child([$params['department_id']], $this->com_id);
            $ids = db('users')->where(['department_id'=>['in',$ids_a], 'com_id'=>$this->com_id])->column('id');
            $where['ieru.user_id'] = ['in', $ids];
        }
        $params['user_id'] && $where['ieru.user_id'] = $params['user_id'];
        $params['event_name'] && $where['e.name'] = ['like', '%'.$params['event_name'].'%'];
        if($params['integral_b1'] && $params['integral_b2']){
            $where['ieru.integral_b'] = [ ['>=', $params['integral_b1']], ['<=', $params['integral_b2']], 'and'];
        }elseif($params['integral_b1']){
            $where['ieru.integral_b'] = ['>=', $params['integral_b1']];
        }elseif($params['integral_b2']){
            $where['ieru.integral_b'] = ['<=', $params['integral_b2']];
        }
        $params['record_user_id'] && $where['ipb.record_user_id'] = $params['record_user_id'];
        $params['first_check_user_id'] && $where['ipb.first_check_user_id'] = $params['first_check_user_id'];
        $params['last_check_user_id'] && $where['ipb.last_check_user_id'] = $params['last_check_user_id'];
        $params['is_print']!=-1 && $where['ieru.is_print'] = $params['is_print'];

        $department = db('com_department')->where(['com_id'=>$this->com_id])->select();  //部门列表
        $department = toTree($department);
        $department = organization_tree($department);
        $user_list = db('users')->where('com_id','in',[0,$this->com_id])->column('id, name');//所有用户列表

        if(input('export') == 1){
            $list = db('com_integral_event_relation_users')->alias('ieru')
                ->join('com_integral_prize_buckle_relation_event ipbre', 'ipbre.id=ieru.event_id', 'LEFT')
                ->join('com_integral_prize_buckle ipb', 'ipb.id=ipbre.prize_buckle_id', 'LEFT')
                ->join('com_event e', 'e.id=ipbre.event_id', 'LEFT')
                ->field([
                    'ieru.id', 'ieru.user_id', 'ieru.integral_b', 'ieru.is_print',
                    'ipbre.event_desc',
                    'ipb.prize_buckle_time', 'ipb.record_user_id','ipb.first_check_user_id','ipb.last_check_user_id',
                    'e.id'=>'e_id', 'e.name'
                ])
                ->where($where)
                ->order('ipb.prize_buckle_time desc')
                ->select();
            $this->index_explode($list, $user_list);
        }else{
            $list = db('com_integral_event_relation_users')->alias('ieru')
                ->join('com_integral_prize_buckle_relation_event ipbre', 'ipbre.id=ieru.event_id', 'LEFT')
                ->join('com_integral_prize_buckle ipb', 'ipb.id=ipbre.prize_buckle_id', 'LEFT')
                ->join('com_event e', 'e.id=ipbre.event_id', 'LEFT')
                ->field([
                    'ieru.id', 'ieru.user_id', 'ieru.integral_b', 'ieru.is_print',
                    'ipbre.event_desc',
                    'ipb.prize_buckle_time', 'ipb.record_user_id','ipb.first_check_user_id','ipb.last_check_user_id',
                    'e.id'=>'e_id', 'e.name'
                ])
                ->where($where)
                ->order('ipb.prize_buckle_time desc')
                ->paginate('',false,page_param());
        }
//        var_dump($list);die;
        $data = [
            'department'=>$department,
            'list'=>$list,
            'user_list'=>$user_list,
            'is_print_arr'=>[0=>'未打印', 1=>'已打印'],
            'prize_buckle_time'=>$prize_buckle_time,
        ];
        $role_id = session("user_com")['role_id'];
        $this->assign('role_id',$role_id);
        $this->assign($data);
        return $this->fetch();
    }
    //我的奖票
    public function mine(){
        $where = [
            'ipb.status'=>2,
            'ieru.com_id'=>$this->com_id,
            'ieru.is_lottery_ticket'=>1
        ];
        $where['ieru.user_id'] = $this->user_id;
        $department = db('com_department')->where(['com_id'=>$this->com_id])->select();  //部门列表
        $department = toTree($department);
        $department = organization_tree($department);
        $user_list = db('users')->where(['com_id'=>$this->com_id])->column('id, name');//所有用户列表

        $list = db('com_integral_event_relation_users')->alias('ieru')
            ->join('com_integral_prize_buckle_relation_event ipbre', 'ipbre.id=ieru.event_id', 'LEFT')
            ->join('com_integral_prize_buckle ipb', 'ipb.id=ipbre.prize_buckle_id', 'LEFT')
            ->join('com_event e', 'e.id=ipbre.event_id', 'LEFT')
            ->field([
                'ieru.id', 'ieru.user_id', 'ieru.integral_b', 'ieru.is_print',
                'ipbre.event_desc',
                'ipb.prize_buckle_time', 'ipb.record_user_id','ipb.first_check_user_id','ipb.last_check_user_id',
                'e.id'=>'e_id', 'e.name'
            ])
            ->where($where)
            ->order('ipb.prize_buckle_time desc')
            ->paginate('',false,page_param());

        $data = [
            'department'=>$department,
            'list'=>$list,
            'user_list'=>$user_list,
            'is_print_arr'=>[0=>'未打印', 1=>'已打印'],
        ];
        $this->assign($data);
        return $this->fetch();
    }

    //奖票事件导出
    public function index_explode_1($list, $user_list){
        $is_print_arr = [0=>'未打印', 1=>'已打印'];
        require EXTEND_PATH.'Export.php';
        $key = ['奖扣对象', '奖扣时间', '事件名称', 'B分', '记录人', '初审人', '终审人', '奖票状态', '事件描述'];
        $val = [];
        foreach ($list as $k => $v) {
            $val[] = [
                $user_list[$v['user_id']],
                date('Y-m-d', $v['prize_buckle_time']),
                $v['name'],
                $v['integral_b'],
                $user_list[$v['record_user_id']],
                $user_list[$v['first_check_user_id']],
                $user_list[$v['last_check_user_id']],
                $is_print_arr[$v['is_print']],
                $v['event_desc'],
            ];
        }
        new \Export($key, $val, '奖票事件');
        die;
    }
    //奖票事件导出@stone
    public function index_explode($list, $user_list){
        $is_print_arr = [0=>'未打印', 1=>'已打印'];
        $key = ['奖扣对象', '奖扣时间', '事件名称', 'B分', '记录人', '初审人', '终审人', '奖票状态', '事件描述'];
        $val = [];
        foreach ($list as $k => $v) {
            $val[] = [
                $user_list[$v['user_id']],
                date('Y-m-d', $v['prize_buckle_time']),
                $v['name'],
                $v['integral_b'],
                $user_list[$v['record_user_id']],
                $user_list[$v['first_check_user_id']],
                $user_list[$v['last_check_user_id']],
                $is_print_arr[$v['is_print']],
                $v['event_desc'],
            ];
        }
        $name = '奖票事件';
        //导出excel
        Export::excel($key,$val,$name,20,['C']);
    }
    //员工视图导出@stone
    public function staff_view_explode($list){
        $key = ['月份', '员工姓名', '员工工号', '部门名称', '奖票总数', '已打印', '未打印'];
        $val = [];
        foreach ($list as $k => $v) {
            $val[] = [
                $v['month'],
                $v['user_name'],
                $v['job_number'],
                $v['department_name'],
                $v['ticket_num'],
                $v['print_yes'],
                $v['print_no'],
            ];
        }
        $name = '员工视图';
        //导出excel
        Export::excel($key,$val,$name,20,['C']);
    }

    //奖票打印
    public function printer(){
        $id = input('id/a', []);//奖票事件列表id
        if(empty($id)){
            return return_json(1,'id不能为空');
        }
        $where = [
            'ipb.status'=>2,
            'ieru.is_lottery_ticket'=>1
        ];
        $where['ieru.id'] = ['in',$id];
        $info = db('com_integral_event_relation_users')->alias('ieru')
            ->join('com_integral_prize_buckle_relation_event ipbre', 'ipbre.id=ieru.event_id', 'LEFT')
            ->join('com_integral_prize_buckle ipb', 'ipb.id=ipbre.prize_buckle_id', 'LEFT')
            ->join('com_event e', 'e.id=ipbre.event_id', 'LEFT')
            ->field([
                'ieru.id', 'ieru.user_id', 'ieru.integral_b', 'ieru.is_print',
                'ipbre.event_desc',
                'ipb.prize_buckle_time', 'ipb.record_user_id','ipb.first_check_user_id','ipb.last_check_user_id',
                'e.id'=>'e_id', 'e.name'
            ])
            ->where($where)
            ->select();
        $user_list = db('users')->where(['com_id'=>$this->com_id])->column('id, name','id');//所有用户列表
        foreach ($info as $key=>$value){
            $info[$key]['user_name'] = $user_list[$value['user_id']];
            $info[$key]['first_check_user_name'] = $user_list[$value['first_check_user_id']]??'管理员';
            $info[$key]['last_check_user_name'] = $user_list[$value['last_check_user_id']]??'管理员';
            $info[$key]['prize_buckle_time'] = date('Y年m月d日', $value['prize_buckle_time']);
        }
        return return_json(0,'成功',$info);
    }
    //更新奖票打印状态
    public function printerUpdate()
    {
        $params = input();
        $ids = $params['id'];
        //判断打印状态
        $where = [];
        $where['id'] = ['in',$ids];
        $where['is_print'] = 1;
        $users = M('com_integral_event_relation_users')->where($where)->find();
        if(!empty($users)){
            return return_json(1,'打印状态有误');
        }else{
            db('com_integral_event_relation_users')->where('id', 'in', $ids)->update(['is_print'=>1]);
            return return_json(0);
        }
    }
    //修改奖票打印状态
    public function update_status()
    {
        $params = input();
        $ids = $params['ids'];
        //判断打印状态
        $where = [];
        $where['id'] = ['in',$ids];
        $where['is_print'] = 0;
        $users = M('com_integral_event_relation_users')->where($where)->find();
        if(!empty($users)){
            return return_json(1,'打印状态有误');
        }else{
            db('com_integral_event_relation_users')->where('id', 'in', $ids)->update(['is_print'=>0]);
            return return_json(0);
        }
    }

    /**
     * 员工视图
     */
    public function staff_view(){
        //奖扣时间
        $prize_buckle_time = input('prize_buckle_time', date('Y-m-1').' - '.date('Y-m-d'));
//        $_GET['prize_buckle_time'] = $prize_buckle_time;
        $prize_buckle_time_arr = explode(' - ', $prize_buckle_time);
//        count($prize_buckle_time_arr)!=2 && die;
        $prize_buckle_time_arr[0] = strtotime($prize_buckle_time_arr[0]??0);
        $prize_buckle_time_arr[1] = strtotime($prize_buckle_time_arr[1]??0);
//        if(!$prize_buckle_time_arr[0] || !$prize_buckle_time_arr[1]){
//            die;
//        }
//        $prize_buckle_time_arr[1] += 86399;

        $department = db('com_department')->where(['com_id'=>$this->com_id])->column('id,pid,name');  //部门列表
        if(input('export') == 1) {
            //用户数组
            $user_list = db('users')->where(['com_id'=>$this->com_id])->column('id, name, department_id, job_number');
            //月份范围 用于后续分组列表
            $month_range = []; //每个元素为某个月的开始到结束时间戳
            $start    = new \DateTime(date('Y-m-d', $prize_buckle_time_arr[0]));
            $end      = new \DateTime(date('Y-m-d', $prize_buckle_time_arr[1]));
            $interval = \DateInterval::createFromDateString('1 month');
            $period   = new \DatePeriod($start, $interval, $end);
            foreach ($period as $k=>$v) {
                $month_str = $v->format("Y-m"); //当前遍历的月
                $day_num = date("t",strtotime($month_str)); //当前遍历月的天数
                $month_range[$k] = [
                    'start_time'=>strtotime($month_str),
                    'end_time'=>strtotime($month_str)+$day_num*86399,
                ];
            }
            //其他查询条件
            $params = [
                'department_id'=>input('department_id', 0, 'intval'),
                'name'=>urldecode(trim(input('name', '', 'addslashes'))),
                'job_number'=>trim(input('job_number', '', 'addslashes')),
            ];
            $where = [
                'ipb.prize_buckle_time'=>[ ['>=',$prize_buckle_time_arr[0]], ['<=',$prize_buckle_time_arr[1]], 'and'],
                'ipb.status'=>2,
                'ipb.com_id'=>$this->com_id,
                'ieru.is_lottery_ticket'=>1
            ];
            $params['department_id'] && $where['u.department_id'] = $params['department_id'];
            $params['name'] && $where['u.name'] = ['like', '%'.$params['name'].'%'];
            $params['job_number'] && $where['u.job_number'] = $params['job_number'];

            //总的奖扣时间范围所有数据
            $list = db('com_integral_prize_buckle')->alias('ipb')
                ->join('com_integral_prize_buckle_relation_event ipbre', 'ipbre.prize_buckle_id=ipb.id', 'LEFT')
                ->join('com_integral_event_relation_users ieru', 'ieru.event_id=ipbre.id', 'LEFT')
                ->join('users u', 'u.id=ieru.user_id', 'LEFT')
                ->field([
                    'ipb.prize_buckle_time',
                    'ieru.user_id', 'ieru.is_print',
                    'u.name', 'u.job_number', 'u.department_id',
                ])
                ->where($where)->select();
//            var_dump($list);die;
            $user_ids = array_unique(array_column($list, 'user_id'));
            foreach ($month_range as $k=>$v) {
                //遍历列表查找对应月份下用户
                $month_range[$k]['user_list'] = [];
                foreach($list as $k2=>$v2){
                    if( $v2['prize_buckle_time'] >= $v['start_time'] && $v2['prize_buckle_time'] <= $v['end_time'] ){
                        $print_yes = 0;
                        $print_no = 0;
                        $v2['is_print'] ? $print_yes = 1 : $print_no = 1;
                        if( !isset($month_range[$k]['user_list'][$v2['user_id']]) ){
                            $month_range[$k]['user_list'][$v2['user_id']] = ['ticket_num'=>1, 'print_yes'=>$print_yes, 'print_no'=>$print_no];
                        }else{
                            $month_range[$k]['user_list'][$v2['user_id']]['ticket_num']++;
                            $month_range[$k]['user_list'][$v2['user_id']]['print_yes'] += $print_yes;
                            $month_range[$k]['user_list'][$v2['user_id']]['print_no'] += $print_no;
                        }
                    }
                }
            }
            $month_range_list = [];//返回数据
            //遍历用户id数组
            foreach($user_ids as $k=>$v){
                foreach($month_range as $k2=>$v2){
                    if($v2['user_list']){
                        //遍历各个月份的用户列表
                        foreach($v2['user_list'] as $k3=>$v3){
                            if($k3 == $v){
                                $month_range_list[] = [
                                    'month'=>date('Y-m', $v2['start_time']),
                                    'user_id'=>$k3,
                                    'user_name'=>$user_list[$k3]['name'],
                                    'job_number'=>$user_list[$k3]['job_number'],
                                    'department_name'=>$department[$user_list[$k3]['department_id']]['name'],
                                    'ticket_num'=>$v3['ticket_num'],
                                    'print_yes'=>$v3['print_yes'],
                                    'print_no'=>$v3['print_no'],
                                ];
                            }
                        }
                    }
                }
            }
            $this->staff_view_explode($month_range_list);
        }
        if(request()->isPost()){
            //用户数组
            $user_list = db('users')->where(['com_id'=>$this->com_id])->column('id, name, department_id, job_number');
            //月份范围 用于后续分组列表
            $month_range = []; //每个元素为某个月的开始到结束时间戳
            $start    = new \DateTime(date('Y-m-d', $prize_buckle_time_arr[0]));
            $end      = new \DateTime(date('Y-m-d', $prize_buckle_time_arr[1]));
            $interval = \DateInterval::createFromDateString('1 month');
            $period   = new \DatePeriod($start, $interval, $end);
            foreach ($period as $k=>$v) {
                $month_str = $v->format("Y-m"); //当前遍历的月
                $day_num = date("t",strtotime($month_str)); //当前遍历月的天数
                $month_range[$k] = [
                    'start_time'=>strtotime($month_str),
                    'end_time'=>strtotime($month_str)+$day_num*86399,
                ];
            }
            //其他查询条件
            $params = [
                'department_id'=>input('department_id', 0, 'intval'),
                'name'=>urldecode(trim(input('name', '', 'addslashes'))),
                'job_number'=>trim(input('job_number', '', 'addslashes')),
            ];
            $where = [
                'ipb.prize_buckle_time'=>[ ['>=',$prize_buckle_time_arr[0]], ['<=',$prize_buckle_time_arr[1]], 'and'],
                'ipb.status'=>2,
                'ipb.com_id'=>$this->com_id,
                'ieru.is_lottery_ticket'=>1
            ];
            $params['department_id'] && $where['u.department_id'] = $params['department_id'];
            $params['name'] && $where['u.name'] = ['like', '%'.$params['name'].'%'];
            $params['job_number'] && $where['u.job_number'] = $params['job_number'];

            //总的奖扣时间范围所有数据
            $list = db('com_integral_prize_buckle')->alias('ipb')
                ->join('com_integral_prize_buckle_relation_event ipbre', 'ipbre.prize_buckle_id=ipb.id', 'LEFT')
                ->join('com_integral_event_relation_users ieru', 'ieru.event_id=ipbre.id', 'LEFT')
                ->join('users u', 'u.id=ieru.user_id', 'LEFT')
                ->field([
                    'ipb.prize_buckle_time',
                    'ieru.user_id', 'ieru.is_print',
                    'u.name', 'u.job_number', 'u.department_id',
                ])
                ->where($where)->select();
//            var_dump($list);die;
            $user_ids = array_unique(array_column($list, 'user_id'));
            foreach ($month_range as $k=>$v) {
                //遍历列表查找对应月份下用户
                $month_range[$k]['user_list'] = [];
                foreach($list as $k2=>$v2){
                    if( $v2['prize_buckle_time'] >= $v['start_time'] && $v2['prize_buckle_time'] <= $v['end_time'] ){
                        $print_yes = 0;
                        $print_no = 0;
                        $v2['is_print'] ? $print_yes = 1 : $print_no = 1;
                        if( !isset($month_range[$k]['user_list'][$v2['user_id']]) ){
                            $month_range[$k]['user_list'][$v2['user_id']] = ['ticket_num'=>1, 'print_yes'=>$print_yes, 'print_no'=>$print_no];
                        }else{
                            $month_range[$k]['user_list'][$v2['user_id']]['ticket_num']++;
                            $month_range[$k]['user_list'][$v2['user_id']]['print_yes'] += $print_yes;
                            $month_range[$k]['user_list'][$v2['user_id']]['print_no'] += $print_no;
                        }
                    }
                }
            }
            $month_range_list = [];//返回数据
            //遍历用户id数组
            foreach($user_ids as $k=>$v){
                foreach($month_range as $k2=>$v2){
                    if($v2['user_list']){
                        //遍历各个月份的用户列表
                        foreach($v2['user_list'] as $k3=>$v3){
                            if($k3 == $v){
                                $month_range_list[] = [
                                    'month'=>date('Y-m', $v2['start_time']),
                                    'user_id'=>$k3,
                                    'user_name'=>$user_list[$k3]['name'],
                                    'job_number'=>$user_list[$k3]['job_number'],
                                    'department_name'=>$department[$user_list[$k3]['department_id']]['name'],
                                    'ticket_num'=>$v3['ticket_num'],
                                    'print_yes'=>$v3['print_yes'],
                                    'print_no'=>$v3['print_no'],
                                ];
                            }
                        }
                    }
                }
            }
//            var_dump(input());die;

            $p = input('p', 1, 'intval');
            $count = count($month_range_list);
            $show_item = 11;//每页显示多少条
            $add_tmp = 0;
            $returnList = [];
            $arrIndex = $p*$show_item-$show_item;//数组起始下标
            for($i=$arrIndex; $i<$count; $i++){
                if($add_tmp >= $show_item){
                    break;
                }
                $add_tmp++;
                $returnList[] = $month_range_list[$i];
            }
            $data = ['list'=>$returnList, 'count'=>$count];

            return json($data);
        }

        $department = toTree($department);
        $department = organization_tree($department);

        $data = [
            'list'=>[],
            'prize_buckle_time'=>$prize_buckle_time,
            'department'=>$department,
        ];
        $this->assign($data);
        return $this->fetch();
    }

    /**
     * 奖票活动
     */
    public function activity(Request $request){
        $params = [
            'name'=>trim(input('name', '', 'addslashes'))
        ];
        $where = ['com_id'=>$this->com_id];
        $params['name'] && $where['name'] = ['like', '%'.$params['name'].'%'];
        $list = db('com_activity')->where($where)->order('end_time desc')->paginate('',false,page_param());
        $this->assign('list',$list);
        return $this->fetch();
    }
    //奖票活动编辑
    public function activity_edit(Request $request){
        if(request()->isPost()){
            return $this->activity_store();
        }
        if(input('id')){
            $where = ['id'=>input('id', 0, 'intval'), 'com_id'=>$this->com_id];
            $info = db('com_activity')->where($where)->find();
            $info['img1'] = getImageUrl($info['img']);
            $info['info'] = json_decode($info['info'],true);
//            var_dump($info);die;

        }else{
            $info = [];
        }
        $this->assign('info', $info);
        return $this->fetch();
    }
    private function activity_store(){
        $params = input();
        $result = $this->validate(
            $params,
            [
                'name|活动名称'  => 'require|max:50',
                'end_time|活动报名截止时间'  => 'require',
                'draw_time|抽奖时间'  => 'require',
//                'apply_max|报名最大人次'  => 'require|number',
                'img|活动图片'  => 'require|max:255',
            ]
        );
        if(true !== $result){
            return $this->ajaxReturn(1, $result);
        }
        $info_index = 0;
        $info = [];
//        var_dump($params['info']);die;
        if(empty($params['info'])){
            return $this->ajaxReturn(1,"抽奖人数为空");
        }
        //多轮抽奖
        foreach($params['info'] as $k=>$v){
            if(empty($v)){
                return $this->ajaxReturn(1,"抽奖人数为空");
//                unset($params['info'][$k]);
            }else{
                if($v < 0){
                    return $this->ajaxReturn(1,"抽奖人数不能为负数");
                }
                $info_index++;
                $info[$k]['number'] = $info_index;
                $info[$k]['sum'] = $v;
                $info[$k]['status'] = 0;
            }
        }
        $params['info'] = json_encode($info);
//        if(!$params['info']){
//            return $this->ajaxReturn(1,"抽奖人数为空");
//        }
        $params['draw_time'] = strtotime($params['draw_time']);
        $params['end_time'] = strtotime($params['end_time']);
        if($params['end_time'] > $params['draw_time']){
            return $this->ajaxReturn(1, '活动开始时间不能小于报名结束时间');
        }
        if($params['end_time'] < time()){
            return $this->ajaxReturn(1, '报名结束时间不能小于当前时间');
        }
        $where = ['com_id'=>$this->com_id];
        if($params['id']){
            $where['id'] = $params['id'];
//            var_dump($params);die;
            db('com_activity')->where($where)->update($params);
        }else{
            $params['com_id'] = $this->com_id;
            $params['create_time'] = time();
            db('com_activity')->insert($params);
        }
        return $this->ajaxReturn(0,"成功", url(CONTROLLER_NAME.'/activity'));
    }
    //奖票活动抽奖
    public function activity_draw(Request $request){
        $id = input('id', 0, 'intval');//活动id
        $activity = db('com_activity')->where(['id'=>$id, 'com_id'=>$this->com_id])->find();//奖票活动详情
        !$activity && $this->error('活动有误');
        //获奖记录
        $activity_log = db('com_activity_log')->where(['activity_id'=>$id, 'com_id'=>$this->com_id,])->column('id, user_id, number, content, create_time');
        $user_ids = array_unique(array_column($activity_log, 'user_id'));
        $user_list = db('users')->where(['id'=>['in', $user_ids]])->column('id, name');
        $relation_users_num = db('com_activity_relation_users')->where(['activity_id'=>$id, 'com_id'=>$this->com_id])->count();//参与活动的用户数
        $activity['info'] = json_decode($activity['info'], true);
        $num_index = 0;
        $data = [
            'relation_users_num'=>$relation_users_num,//奖票总数
            'activity'=>$activity,//活动详情
            'user_list'=>$user_list,//用户列表
            'activity_log'=>$activity_log,//该活动的获奖记录
        ];
        $this->assign($data);
        return $this->fetch();
    }
    //开始抽奖
    public function activity_start(){
        $activity_id = input('id', 0, 'intval');//活动id
        $lun = input('lun', 0, 'intval');//活动的第几轮抽奖
        $activity = db('com_activity')->where(['id'=>$activity_id, 'com_id'=>$this->com_id])->find();
        !$activity && $this->error('活动不存在');
        $activity['info'] = json_decode($activity['info'], true);
        if(!isset($activity['info'][$lun-1]) || $activity['info'][$lun-1]['status'] == 1){
            $this->error('该轮抽奖不存在');
        }
        //报名活动关联用户表
        $activity_relation_users = db('com_activity_relation_users')->where(['activity_id'=>$activity_id, 'status'=>0])->column('id, user_id, event_id');
        $activity_relation_users_ids = array_column($activity_relation_users, 'id');//等待被抽奖的报名活动关联用户表id数组
        $event_ids = array_column($activity_relation_users, 'event_id'); //积分奖扣事件参与人关联表id数组
        $select_ids = []; //已被抽中的报名活动关联用户表id数组
        //循环遍历最大值为该轮抽奖的奖励个数
        for($i=0; $i<$activity['info'][$lun-1]['sum']; $i++){
            if($activity_relation_users_ids){
                $tmp_id = array_rand($activity_relation_users_ids, 1);
                $select_ids[] = $activity_relation_users_ids[$tmp_id];
                unset($activity_relation_users_ids[$tmp_id]);
            }else{
                break;
            }
        }
        //报名活动关联用户表的事件信息
        $event_list = db('com_integral_event_relation_users')->alias('ieru')
            ->join('com_integral_prize_buckle_relation_event ipbre', 'ipbre.id=ieru.event_id', 'LEFT')
            ->join('com_event e', 'e.id=ipbre.event_id', 'LEFT')
            ->where(['ieru.id'=>['in', $event_ids]])
            ->column('ieru.id, ieru.integral_b, ipbre.create_time, e.name');
        Db::startTrans();
        try {
            //修改选中的中奖状态
            db('com_activity_relation_users')->where(['id' => ['in', $select_ids]])->update(['status' => 1]);
            $insert_data = [];//获奖记录表插入数据
            $now_time = time();
            foreach ($activity_relation_users as $k => $v) {
                if(in_array($v['id'],$select_ids)) {
                    $insert_data[] = [
                        'com_id' => $this->com_id,
                        'user_id' => $v['user_id'],
                        'activity_id' => $activity_id,
                        'content' => $event_list[$v['event_id']]['name'] . ' 获得' . $event_list[$v['event_id']]['integral_b'] . ' B分',
                        'create_time' => $now_time,
                        'number' => $lun
                    ];
                }
            }
            db('com_activity_log')->insertAll($insert_data);
            $activity['info'][$lun-1]['status'] = 1;
            $activity['info'] = json_encode($activity['info']);
            db('com_activity')->where(['id' => $activity_id])->update(['info' => $activity['info']]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('抽奖失败');
        }
//        $this->success('抽奖成功', url('ticket/activity_draw',['id' => $activity_id]));
        $this->redirect(url('ticket/activity_draw',['id' => $activity_id]));
    }
    //开始抽奖@stone
    public function start_draw(){
        $activity_id = input('id', 0, 'intval');//活动id
        $lun = input('lun', 0, 'intval');//活动的第几轮抽奖
        
        $activity = db('com_activity')->where(['id'=>$activity_id, 'com_id'=>$this->com_id])->find();
        if(empty($activity)){
            return return_json(1,'活动不存在');
        }
        if(empty($lun)){
            return return_json(1,'第几轮不存在');
        }
        $activity['info'] = json_decode($activity['info'], true);
        if(!isset($activity['info'][$lun-1]) || $activity['info'][$lun-1]['status'] == 1){
            $this->error('该轮抽奖不存在');
            return return_json(1,'该轮抽奖已结束');
        }
        //报名活动关联用户表
        $activity_relation_users = M('com_activity_relation_users a')
            ->join('users b','b.id=a.user_id','left')
            ->join('com_integral_event_relation_users c', 'c.id=a.event_id', 'LEFT')
            ->join('com_integral_prize_buckle_relation_event d', 'd.id=c.event_id', 'LEFT')
            ->join('com_event e', 'e.id=d.event_id', 'LEFT')
            ->where(['a.activity_id'=>$activity_id, 'a.status'=>0])->column('a.id, a.user_id, a.event_id,c.integral_b,b.name,e.name event_name,d.create_time','a.id');
        $event_ids = array_column($activity_relation_users, 'id'); //积分奖扣事件参与人关联表id数组
        $sum = $activity['info'][$lun-1]['sum']; //本轮抽奖数量
        //本轮已抽数据
        $use_sum = M('com_activity_log')->where(['activity_id'=>$activity_id,'number'=>$lun])->count();
        $data = [
            'list'=>$activity_relation_users,
            'ids'=>$event_ids,
            'sum'=>$sum,
            'use_sum'=>$use_sum
        ];
        return return_json(0,'成功',$data);
    }
    //抽奖结束@stone
    public function end_draw(){
        $id = I('id',0);
        if(empty($id)){
            return return_json(1,'id不能为空');
        }
        $activity_id = input('activity_id', 0, 'intval');//活动id
        $lun = input('lun', 0, 'intval');//活动的第几轮抽奖
        $activity = db('com_activity')->where(['id'=>$activity_id, 'com_id'=>$this->com_id])->find();
        if(empty($activity)){
            return return_json(1,'活动不存在');
        }
        if(empty($lun)){
            return return_json(1,'第几轮不存在');
        }
        $activity['info'] = json_decode($activity['info'], true);
        if(!isset($activity['info'][$lun-1]) || $activity['info'][$lun-1]['status'] == 1){
            return return_json(1,'该轮抽奖已结束');
        }
        $activity_relation_users = M('com_activity_relation_users a')
            ->join('users b','b.id=a.user_id','left')
            ->join('com_integral_event_relation_users c', 'c.id=a.event_id', 'LEFT')
            ->join('com_integral_prize_buckle_relation_event d', 'd.id=c.event_id', 'LEFT')
            ->join('com_event e', 'e.id=d.event_id', 'LEFT')
            ->where('a.id',$id)
            ->field('a.id, a.user_id, a.event_id,c.integral_b,b.name,e.name event_name,d.create_time')
            ->find();
        $insert_data =
            [
                'com_id' => $this->com_id,
                'user_id' => $activity_relation_users['user_id'],
                'activity_id' => $activity_id,
                'content' => $activity_relation_users['event_name'] . ' 获得' . $activity_relation_users['integral_b'] . ' B分',
                'create_time' => time(),
                'number' => $lun
            ];
        DB::startTrans();
        try{
            DB::commit();
            //添加抽奖记录
            M('com_activity_log')->insert($insert_data);
            //修改中奖用户
            M('com_activity_relation_users')->where('id',$id)->update(['status'=>1]);
            //判断是否已抽完
            $sum = $activity['info'][$lun-1]['sum'];
            $use_sum = M('com_activity_log')->where(['activity_id'=>$activity_id,'number'=>$lun])->count();
            $status = 0;
            if($use_sum >= $sum ){
                //修改抽奖状态
                $status = 1;
                $activity['info'][$lun-1]['status'] = 1;
                $activity['info'] = json_encode($activity['info']);
                db('com_activity')->where(['id' => $activity_id])->update(['info' => $activity['info']]);
            }
            $list = M('com_activity_log a')
                ->join('users b','b.id=a.user_id','left')
                ->where(['a.activity_id'=>$activity_id,'a.number'=>$lun])
                ->field("b.name,a.content,a.create_time")
                ->select();
            foreach ($list as $key=>$value){
                $list[$key]['create_time']=date('Y-m-d',$value['create_time']);
            }
            $data=[
                'sum'=>$sum,
                'use_sum'=>$use_sum,
                'status'=>$status,
                'list'=>$list,
            ];
            return return_json(0,'成功',$data);
        }catch (\Exception $e){
            DB::rollback();
            return return_json(1,$e->getMessage());
        }
    }

}
